/*
 * 版权所有 ( c ) 联想集团有限公司 2005-2009 保留所有权利。
 * 项目：	Lenovo Push Service
 * 文件名：	ImageReadExample.java
 * 版本:    1.0
 * 描述：	
 * 作者：	刘兵召
 * 日期：	May 10, 2010 
 * 修改历史：
 * 【时间】		【修改者】	【修改内容】
 */
package com.feng.demo.jakartacommons.sanselan;

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.sanselan.ImageReadException;
import org.apache.sanselan.Sanselan;
import org.apache.sanselan.SanselanConstants;
import org.apache.sanselan.common.IBufferedImageFactory;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageReadExample {
	public static void main(String[] args) throws ImageReadException,
			IOException {
		File file = new File("d:/2010-04-15012728-12713092483130463.png");
		BufferedImage image = imageReadExample(file);
		saveImage(image, "d:/a.png");
	}

	public static BufferedImage imageReadExample(File file)
			throws ImageReadException, IOException {
		Map params = new HashMap();
		// set optional parameters if you like
		//params.put(SanselanConstants.BUFFERED_IMAGE_FACTORY,new ManagedImageBufferedImageFactory());
		//params.put(SanselanConstants.PARAM_KEY_VERBOSE, Boolean.TRUE);
		// read image
		BufferedImage image = Sanselan.getBufferedImage(file);
		return image;
	}

	public static class ManagedImageBufferedImageFactory implements IBufferedImageFactory {

		public BufferedImage getColorBufferedImage(int width, int height,
				boolean hasAlpha) {
			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			GraphicsDevice gd = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gd.getDefaultConfiguration();
			return gc.createCompatibleImage(width, height,Transparency.TRANSLUCENT);
		}

		public BufferedImage getGrayscaleBufferedImage(int width, int height,
				boolean hasAlpha) {
			return getColorBufferedImage(width, height, hasAlpha);
		}
	}

	/**
	 * @throws IOException 
	 * @throws ImageFormatException 
	 * 
	 */
	public static void saveImage(BufferedImage bufferImage,String filePath) throws ImageFormatException, IOException {
		FileOutputStream output = new FileOutputStream(filePath);
		JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(output);
		jpg.encode(bufferImage);
		output.close();
	}
}
